package gameuserlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/common/auth"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/utils"
	"time"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenGameTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenGameTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenGameTokenLogic {
	return &GenGameTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 生成游戏token
func (l *GenGameTokenLogic) GenGameToken(in *pb.GenGameTokenReq) (*pb.GenGameTokenResp, error) {
	defer utils.RecoverPanic()

	var rsp pb.GenGameTokenResp
	var err error
	rsp.Token, err = l.getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, time.Now().Unix(), l.svcCtx.Config.JwtAuth.AccessExpire, in.OpenId, in.Nickname)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	return &rsp, nil
}

func (l *GenGameTokenLogic) getJwtToken(secretKey string, iat, seconds int64, openId int64, nickname string) (string, error) {
	cl := make(map[string]interface{}, 0)
	cl[ctxdata.CtxKeyJwtOpenId] = openId
	cl[ctxdata.CtxKeyJwtNickname] = nickname

	return auth.GetJwtToken(secretKey, iat, seconds, cl)
}
